const express = require('express')
const router = express.Router()
const User = require('../db/users')
const Order = require('../db/store_order.js')
const Cart = require('../db/cart')
const jwt = require('jsonwebtoken')
const alipaySdk = require('../db/alipay')
const AlipayFormData = require('alipay-sdk/lib/form').default

//生成订单
router.post('/api/addOrder', (req, res) => {
  let token = req.headers.authorization
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(val => {
    let tel = val.tel
    //订单信息
    let orderArr = JSON.parse(req.body.orderArr)
    //生成订单号,时间戳+随机六位数
    function setTimeDateFmt(s) {
      return s < 10 ? '0' + s : s
    }

    function randomNumber() {
      const now = new Date()
      let month = now.getMonth() + 1
      let day = now.getDate()
      let hour = now.getHours()
      let minutes = now.getMinutes()
      let seconds = now.getSeconds()
      month = setTimeDateFmt(month)
      day = setTimeDateFmt(day)
      hour = setTimeDateFmt(hour)
      minutes = setTimeDateFmt(minutes)
      seconds = setTimeDateFmt(seconds)
      let orderCode = now.getFullYear().toString() + month.toString() + day.toString() + hour.toString() + minutes.toString() + seconds.toString() + Math.floor(Math.random() * 100000 + 900000).toString()
      return orderCode
    }
    //商品列表名称
    let goodsName = []
    //订单商品总金额
    let goodsPrice = 0
    //订单商品总数量
    let goodsNum = 0

    orderArr.forEach(v => {
      goodsName.push(v.goods_name)
      goodsPrice += v.goods_price * v.goods_num
      goodsNum += v.goods_num
    })
    //获取用户id
    User.find({
      tel
    }).then(data => {
      let uId = data[0]._id
      Order.create({
        uId,
        order_id: randomNumber(),
        order_name: goodsName,
        order_price: goodsPrice,
        order_num: goodsNum,
        order_status: 1
      }).then(data => {
        return res.send({
          code: 200,
          success: true,
          data
        })
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
//查询订单信息
router.post('/api/selectOrder', (req, res) => {
  let order_id = req.body.orderId
  Order.find({
    order_id
  }).then(data => {
    res.send({
      code: 200,
      success: true,
      data: data[0]
    })
  })
})
//修改订单状态
router.post('/api/submitOrder', (req, res) => {
  let selectList = JSON.parse(req.body.shopArr)
  let orderId = req.body.orderId
  let token = req.headers.authorization
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(val => {
    //修改订单状态1 => 2
    Order.updateMany({
      orderId
    }, {
      order_status: 2
    }).then(data => {
      //删除购物车数据
      selectList.forEach((v, i) => {
        Cart.deleteMany({
          goods_id: v
        }).then(data => {
          if (selectList.length == i + 1) {
            res.send({
              code: 200,
              msg: ''
            })
          }
        })
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
//发起支付
router.post('/api/payment', (req, res) => {
  let token = req.headers.authorization
  new Promise((resolved, rejected) => {
    resolved(jwt.verify(token, 'jwt'))
  }).then(val => {
    let {
      orderId,
      price,
      name
    } = req.body
    //开始对接支付宝api
    const formData = new AlipayFormData()
    //调用setMethod并传入get,会返回可以跳转到支付页面的url
    formData.setMethod('get')
    //支付时的信息
    formData.addField('bizContent', {
      outTradeNo: orderId, //订单号
      productCode: 'FAST_INSTANT_TRADE_PAY', //
      totalAmount: price, //价格
      subject: name, //商品名称
      //body:  '商品描述'
    })
    //支付成功或跳转的链接
    formData.addField('returnUrl', 'http://www.baidu.com')
    //返回promise
    const result = alipaySdk.exec(
      'alipay.trade.page.pay', {}, {
        formData: formData
      }
    )
    //对接支付成功,支付宝方返回的数据
    result.then(resp => {
      res.send({
        data: {
          code: 200,
          success: true,
          msg: '跳转支付页面...',
          paymentUrl: resp
        }
      })
    })
  }).catch(err => {
    return res.send({
      code: 400,
      msg: err.message
    })
  })
})
module.exports = router
